// user模块
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login } from '@/api/user'
const state = {
  token: getToken(),
  userInfo: {
    id: null,
    username: '',
    nickname: '',
    email: '',
    user_pic: null
  }
}

const mutations = {
  // 设置token
  setToken (state, token) {
    state.token = token
    // 同步到缓存
    setToken(token)
  },
  // 移除token
  removeToken (state) {
    state.token = null
    removeToken()
  },
  // 存储个人信息
  setUserInfo (state, info) {
    state.userInfo = { ...info }
  },
  // 修改个人头像
  setAvatar (state, avatar) {
    state.userInfo.user_pic = avatar
  }
}

const actions = {
  async login (context, data) {
    const { token } = await login(data)
    console.log(token)
    context.commit('setToken', token)
  },
  // 退出登录
  logout (context) {
    context.commit('removeToken')
    context.commit('setToken', {})
  },
  // 修改个人信息actions
  changeUserInfo (context, info) {
    context.commit('setUserInfo', info)
  },
  // 修改头像actions
  changeAvatar (context, avatar) {
    context.commit('setAvatar', avatar)
  }
}

export default {
  namespaced: true, // 开启命名空间
  state,
  mutations,
  actions
}
